<template>
  <div>
    <!-- 下拉刷新组件 -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <!-- 上拉加载更多组件 -->
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
        offset="50"
      >
        <!-- 自定义组件：每一个文章item -->
        <ArticleItem
          v-for="obj in list"
          :key="obj.art_id"
          :artObj="obj"
          @dislikeEvent="dislikeFn"
          @reportEvent="reportFn"
          @click.native="itemClickFn(obj.art_id)"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 组件的使用步骤：1. 创建 2. 引入 3. 注册 4. 使用标签
import {
  getAllArticleListAPI,
  articleDislikeAPI,
  reportArticleAPI
} from '@/api'
import ArticleItem from '../../../components/ArticleItem.vue'
import { Notify } from 'vant'
export default {
  props: {
    channelId: Number // 频道ID
  },
  data () {
    return {
      list: [], // 文章列表数组
      loading: false, // 列表加载状态
      finished: false, // 列表加载完成状态
      theTime: new Date().getTime(),
      isLoading: false // 顶部加载的状态
    }
  },
  async created () {
    this.getArticleListFn()
  },
  methods: {
    // 获取文章列表数组
    async getArticleListFn () {
      const res = await getAllArticleListAPI({
        channel_id: this.channelId, // 先默认请求推荐频道数据
        timestamp: this.theTime
      })
      console.log(res)

      this.list = [...this.list, ...res.data.data.results]
      this.theTime = res.data.data.pre_timestamp

      // 上拉触底刷新属性修改
      this.loading = false // 如果不关闭, 底部一直是加载中状态, 下次触底会再触发onLoad
      if (res.data.data.pre_timestamp === null) {
        this.finished = true
      }

      // 下拉刷新属性修改
      this.isLoading = false // 顶部加载状态改为false
    },
    // 上拉加载
    async onLoad () {
      this.getArticleListFn()
    },
    // 下拉刷新数据事件方法
    async onRefresh () {
      this.list = []
      this.theTime = new Date().getTime()
      this.getArticleListFn()
    },
    // 不感兴趣反馈
    async dislikeFn (artId) {
      const res = await articleDislikeAPI({
        target: artId
      })
      console.log(res)
      Notify({ type: 'success', message: '反馈成功' })
    },
    // 反馈垃圾内容
    async reportFn (id, value) {
      const res = await reportArticleAPI({
        artId: id,
        type: value
      })
      Notify({ type: 'success', message: '举报成功' })
      console.log(res)
    },
    // 文章单元格点击事件
    itemClickFn (id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  },
  components: {
    ArticleItem
  }
}
</script>
<style>
</style>
